import axios from 'axios';
import qs from 'qs'
import { Message } from 'element-ui'

const service = axios.create({
    headers: {
        'Content-Type': 'application/json; charset=utf-8'
      },
    // process.env.NODE_ENV === 'development' 来判断是否开发环境
    // easy-mock服务挂了，暂时不使用了
    //baseURL: 'https://www.easy-mock.com/mock/592501a391470c0ac1fab128',
    timeout: 10000000
});

service.interceptors.request.use(
    config => {
        if (!config.headContype) {
            config.data = qs.stringify(config.data)
            config.headers['Content-Type']='application/x-www-form-urlencoded; charset=UTF-8'
        }
         config.headers['accessToken'] = sessionStorage.getItem('accessToken')
         config.headers['userId'] = sessionStorage.getItem('userId')

        return config;
    },
    error => {
        return Promise.reject();
    }
);

service.interceptors.response.use(
    response => {
        if (response.status === 200) {
            if (response.data.code == '40240003') {
                window.location.href="/"
            }
             else if (response.data.code == undefined) {
                return response.data;
             }
           else if (response.data.code != 20000000) {
                Message.error({message: response.data.message})
                return response.data;
            } 
             else {
                return response.data;
            }
            
        } else {
            Promise.reject();
        }
    },
    error => {
        Message.error({message: '网络超时请稍后再试'})
        return Promise.reject();
    }
);

export default service;
